const api = require('../../../../ws_micro_shop/utils/api.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const app = getApp();
let is_no_more = false;
let is_loading = false;
let p = 2;
let timer = null;
let interval = null;
Page({
  data: {
    hide: 1,
    qrcode: '',
    classa: (app.tabbarindex === 0 ? false : true) || app.siteInfo.tabbar_type === '2',
    theme: app.themeData,
    showpaytypes: false,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-19.png',
      text: '还没有相关预约订单哦~',
    },
    unit: '',
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
  },
  onLoad(opts) {
    let that = this;
    this.setData({
      orgPrice: app.ws_micro_shop_globalData.orgPrice,
    })
    let options = opts || {};
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    let userinfo = wx.getStorageSync('user_info');
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    Number(userinfo.info === 0) && tools.onGetInfo(this, userinfo.auth_mode);
    app.pageOnLoad(this);
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.setData({
      commentSwitch: wx.getStorageSync('store').comment_switch,
      opts: options,
      status: options.status || -1,
      userinfo,
    });
  },
  onShow() {
    this.loadOrderList(this.data.status);
  },
  onHide() {
    interval && clearInterval(interval);
    timer && clearInterval(timer);
  },
  onUnload() {
    interval && clearInterval(interval);
    timer && clearInterval(timer)
  },
  switchList(e) {
    let status = e.currentTarget.dataset.status;
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.setData({
      order_list: [],
    });
    this.loadOrderList(status);
  },
  onReachBottom() {
    interval && clearInterval(interval);
    let that = this;
    let status = that.data.status;
    if (is_loading || is_no_more) {
      return;
    }
    is_loading = true;
    app.ws_micro_shoprequest({
      url: api.book.order_list,
      data: {
        status,
        page: p,
      },
      success: function (res) {
        if (res.code === 0) {
          let list = res.data.list;
          let order_list = that.data.order_list.concat(list);
          that.setData({
            order_list,
          });
          (list.length === 0) && (is_no_more = true);
          Math.abs(Number(status)) === 1 && that.timeFormat();
        }
        p++;
      },
      complete: function () {
        is_loading = false;
      },
    });
  },
  loadOrderList(stas) {
    let that = this;
    let status = stas;
    (!status) && (status = -1);
    interval && clearInterval(interval);
    that.setData({
      status,
    });
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.book.order_list,
      data: {
        status: that.data.status,
      },
      success: function (res) {
        let { list } = res.data;
        if (res.code === 0) {
          that.setData({
            order_list: list,
          });
          Math.abs(Number(status)) === 1 && that.timeFormat();
        }
        that.setData({
          show_no_data_tip: (list.length === 0),
        });
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },
  orderCancel(e) {
    wx.showModal({
      title: '提示',
      content: '是否取消该预约订单',
      success(res) {
        if (res.confirm) {
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    let id = e.currentTarget.dataset.id;
    app.ws_micro_shoprequest({
      url: api.book.order_cancel,
      data: {
        id,
      },
      success: function (res) {
        if (res.code === 0) {
          app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', { status: 0 }, true);
        }
      },
      complete: function () {
        wx.hideLoading();
      },
    });
        } else if (res.cancel) {
          return;
        }
      }
    })
  },
  orderPay(e) {
    let payment = Number(e.currentTarget.dataset.payment);
    let { orderID: id, userinfo } = this.data;
    wx.showLoading({
      title: '正在提交',
      mask: true,
    });
    this.setData({
      showpaytypes: false,
    });
    if (payment === 0) {
      this.WechatPay(id);
    } else if (payment === 3) {
      this.setData({
        showpaytypes: false,
      });
      this.BalancePay(id);
    } else if (payment === 5) {
      if (userinfo.unionid && userinfo.card) {
        this.CardPay(id);
      } else {
        wx.hideLoading();
        wx.showModal({
          title: '友情提示',
          content: '你还未开通会员卡，是否前往个人中心开通？',
          success: function (res) {
            if (res.confirm) {
              app.util.navigateTo('/ws_micro_shop/pages/user/user', {}, false);
            }
          },
        });
      }
    }
  },
  WechatPay(id) {
    app.ws_micro_shoprequest({
      url: api.book.order_pay,
      data: {
        id,
        pay_type: 'WECHAT_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          let { timeStamp, nonceStr, signType, paySign } = res.data;
          wx.requestPayment({
            timeStamp,
            nonceStr,
            package: res.data.package,
            signType,
            paySign,
            complete: function (e) {
              if (e.errMsg === 'requestPayment:fail' || e.errMsg === 'requestPayment:fail cancel') {
                wx.showModal({
                  title: '提示',
                  content: '订单尚未支付',
                  showCancel: false,
                  confirmText: '确认',
                  success: function (res) {
                    if (res.confirm) {
                      app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', { status: 0 }, true);
                    }
                  },
                });
                return;
              }
              app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', { status: 1 }, true);
            },
          });
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  BalancePay(id) {
    app.ws_micro_shoprequest({
      url: api.book.order_pay,
      data: {
        id,
        pay_type: 'BALANCE_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
            status: 1,
          }, true);
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  CardPay(id) {
    app.ws_micro_shoprequest({
      url: api.book.order_pay,
      data: {
        id,
        pay_type: 'CARD_PAY',
      },
      complete: function () {
        wx.hideLoading();
      },
      success: function (res) {
        if (res.code === 0) {
          app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', {
            status: 1,
          }, true);
        }
        if (res.code === 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },
  goToDetails(e) {
    wx.navigateTo({
      url: '/ws_micro_shop_book/pages/book/order/details?oid=' + e.currentTarget.dataset.id,
    });
  },
  orderQrcode(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let { id, offline_qrcode, order_no } = that.data.order_list[index];
    let orderId = id;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    if (offline_qrcode) {
      that.setData({
        hide: 0,
        qrcode: offline_qrcode,
      });
      wx.hideLoading();
    } else {
      app.ws_micro_shoprequest({
        url: api.book.get_qrcode,
        data: {
          order_no,
        },
        success: function (res) {
          if (res.code === 0) {
            that.setData({
              hide: 0,
              qrcode: res.data.url,
            });
            timer && clearInterval(timer);
            that.Loop(orderId);
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
            });
          }
        },
        complete: function () {
          wx.hideLoading();
        },
      });
    }
  },
  hide() {
    timer && clearInterval(timer);
    this.setData({
      hide: 1,
    });
  },
  showPayType(e) {
    let list = this.data.order_list;
    let { id, idx, payment, discount } = e.currentTarget.dataset;
    this.setData({
      showpaytypes: true,
      orderID: id,
      pay_type_list: list[idx].pay_type_list,
      discountId: discount == 1 ? payment : -1,
    });
  },
  disabledClick() {
    // it`s necessary
  },
  hidePayType() {
    this.setData({
      showpaytypes: false,
    });
  },
  applyRefund(e) {
    let id = e.currentTarget.dataset.id;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.book.apply_refund,
      data: {
        order_id: id,
      },
      success: function (res) {
        if (res.code === 0) {
          wx.showModal({
            title: '提示',
            content: res.msg || '申请退款成功',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                app.util.navigateTo('/ws_micro_shop_book/pages/book/order/order', { status: 3 }, true);
              }
            },
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg || '申请退款失败',
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },
  timeFormat() {
    let that = this;
    interval = setInterval(function () {
      let order_list = that.data.order_list;
      for (let i in order_list) {
        if ({}.hasOwnProperty.call(order_list, i)) {
          let leftTime = order_list[i].leave_time2;
          if (leftTime && leftTime >= 0) {
            let hours = parseInt(leftTime / 60 / 60 % 24, 10);
            let minutes = parseInt(leftTime / 60 % 60, 10);
            let seconds = parseInt(leftTime % 60, 10);
            let timestr = '';
            if (seconds >= 0 && seconds < 10) {
              seconds = '0' + seconds;
              timestr = '00:00:' + seconds;
            } else {
              timestr = '00:00:' + seconds;
            }
            if (minutes >= 0 && minutes < 10) {
              minutes = '0' + minutes;
              timestr = '00:' + minutes + ':' + seconds;
            } else {
              timestr = '00:' + minutes + ':' + seconds;
            }
            if (hours >= 0 && hours < 10) {
              hours = '0' + hours;
              timestr = hours + ':' + minutes + ':' + seconds;
            } else {
              timestr = hours + ':' + minutes + ':' + seconds;
            }
            order_list[i].limit_time = timestr;
          } else if (leftTime && leftTime < 0) {
            order_list.splice(i, 1);
          }
          leftTime >= 0 && (order_list[i].leave_time2 = order_list[i].leave_time2 - 1);
          that.setData({
            order_list,
          });
        }
      }
    }, 1000);
  },
  comment(e) {
    wx.navigateTo({
      url: '/ws_micro_shop/pages/order-comment/order-comment?id=' + e.currentTarget.dataset.id + '&entry=book',
    });
  },
  Loop(id) {
    let that = this;
    timer = setInterval(function () {
      app.ws_micro_shoprequest({
        url: api.default.orderClerk,
        data: {
          order_id: id,
          type: 'book',
        },
        success: function (res) {
          if (res.code === 0) {
            if (Number(res.data) === 1) {
              timer && clearInterval(timer);
              that.setData({
                hide: 1,
              });
              that.loadOrderList(that.data.status);
            }
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
            });
          }
        },
      });
    }, 2000);
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  deleteOrder(e) {
    let that = this;
    let { id: order_id, idx } = e.currentTarget.dataset;
    let orderlist = that.data.order_list;
    wx.showModal({
      title: '提示',
      content: '是否要删除该订单',
      success: res => {
        if (res.confirm) {
          app.ws_micro_shoprequest({
            url: api.order.deleteorder,
            data: {
              order_id,
              type: 'yy',
            },
            success: function (res) {
              if (res.code === 0) {
                orderlist.splice(idx, 1);
                that.setData({
                  order_list: orderlist,
                });
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                });
              } else {
                wx.showToast({
                  title: res.msg || '删除失败',
                  icon: 'none',
                });
              }
            },
          });
        }
      },
    });
  },
});
